package com.xiaoyun.controller;

import com.xiaoyun.bo.AddressBO;
import com.xiaoyun.pojo.UserAddress;
import com.xiaoyun.service.AddressService;
import com.xiaoyun.utils.XYJSONResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@Api("地址相关")
@RestController
@RequestMapping("address")
@RequiredArgsConstructor
public class AddressController {

    private final AddressService addressService;

    @ApiOperation("根据用户id查询收货地址列表")
    @PostMapping("/list")
    public XYJSONResult list(@RequestParam String userId) {
        List<UserAddress> list = addressService.queryAll(userId);
        return XYJSONResult.ok(list);
    }

    @ApiOperation("用户新增地址")
    @PostMapping("/add")
    public XYJSONResult add(@RequestBody @Valid AddressBO addressBo) {
        addressService.addNewUserAddress(addressBo);
        return XYJSONResult.ok();
    }

    @ApiOperation("用户修改地址")
    @PostMapping("/update")
    public XYJSONResult update(@RequestBody @Valid AddressBO addressBo) {
        if (StringUtils.isBlank(addressBo.getAddressId())) {
            return XYJSONResult.errorMsg("");
        }
        addressService.updateUserAddress(addressBo);
        return XYJSONResult.ok();
    }

    @ApiOperation("用户删除地址")
    @PostMapping("/delete")
    public XYJSONResult delete(@RequestParam String userId,
                               @RequestParam String addressId) {
        if (StringUtils.isBlank(userId) || StringUtils.isBlank(addressId)) {
            return XYJSONResult.errorMsg("");
        }
        addressService.deleteUserAddress(userId, addressId);
        return XYJSONResult.ok();
    }

    @ApiOperation("用户设置默认地址")
    @PostMapping("/setDefault")
    public XYJSONResult setDefault(@RequestParam String userId,
                                   @RequestParam String addressId) {
        if (StringUtils.isBlank(userId) || StringUtils.isBlank(addressId)) {
            return XYJSONResult.errorMsg("");
        }
        addressService.updateUserAddressToBeDefault(userId, addressId);
        return XYJSONResult.ok();
    }
}
